package com.dempsey.gateway.service;

import cn.hutool.log.Log;
import cn.hutool.log.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContext;
import org.springframework.security.core.context.SecurityContextImpl;
import org.springframework.security.web.server.context.ServerSecurityContextRepository;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

/**
 * 1. 把header拿到的token放入AuthenticationToken
 *
 * @author zhe.xiao
 * @date 2021-04-14 23:32
 * @description
 */
@Component
public class ScSecurityContextRepository implements ServerSecurityContextRepository {

    private final static Log log = LogFactory.get();

    @Autowired
    ScAuthenticationManager scAuthenticationManager;

    @Override
    public Mono<Void> save(ServerWebExchange exchange, SecurityContext context) {
        return Mono.empty();
    }

    @Override
    public Mono<SecurityContext> load(ServerWebExchange exchange) {
        ServerHttpRequest request = exchange.getRequest();
        String path = request.getURI().getPath();
        log.info("访问地址{}", path);

        String authorization = request.getHeaders().getFirst("Authorization");
        log.info("1. 把header拿到的token放入AuthenticationToken");
        log.info(authorization);

        return scAuthenticationManager
                .authenticate(new UsernamePasswordAuthenticationToken(authorization, null))
                .map(SecurityContextImpl::new);
    }
}